package movie.wrapper;

import javax.jdo.PersistenceManager;
import java.util.List;

public class Caching
{
	Caching cache;
	private static Caching instance = null;
	
	protected Caching() {
	}
	
	public static Caching getInstance() {
		if(instance == null) {
			instance = new Caching();
		}
		return instance;
	}
	
	public void Add(Movie movieObj)
	{
		PersistenceManager pm = movie.wrapper.PMF.get().getPersistenceManager();

        try {
            pm.makePersistent(movieObj);
        } finally {
            pm.close();
        }
	}
	
	@SuppressWarnings("unchecked")
	public Movie Get(String MovieTitle)
	{
		PersistenceManager pm = movie.wrapper.PMF.get().getPersistenceManager();
		
		String query = "select from " + Movie.class.getName() + " where Name == '"+ MovieTitle +"'";
        List<Movie> movie = (List<Movie>)pm.newQuery(query).execute();
        
        if (movie.toArray().length > 0)
        {
        	return movie.get(0);
        }
        else
        {
        	return null;
        }
	}
	
	@SuppressWarnings("unchecked")
	public void Remove(String MovieTitle)
	{
		PersistenceManager pm = movie.wrapper.PMF.get().getPersistenceManager();
		
		String query = "select from " + Movie.class.getName() + " where Name == '"+ MovieTitle +"'";
		List<Movie> movie = (List<Movie>)pm.newQuery(query).execute();
	    
		if (movie.toArray().length > 0)
        {
			pm.deletePersistentAll(movie);
        }
	}
	
	@SuppressWarnings("unchecked")
	public void Clear()
	{
		PersistenceManager pm = movie.wrapper.PMF.get().getPersistenceManager();
		
		String query = "select from " + Movie.class.getName();
		List<Movie> movie = (List<Movie>)pm.newQuery(query).execute();
	    
		if (movie.toArray().length > 0)
        {
			pm.deletePersistentAll(movie);
        }
	}
}